import { Toast } from 'antd-mobile'
import axios from 'axios'
import { getToken, hasToken, setToken } from './storage'
import history from '@/utils/history.js'
import store from '@/store/'
import { saveToken } from '@/store/actions/login'

const baseURL = 'http://geek.itheima.net/v1_0'
const request = axios.create({
    baseURL,
    timeout: 1000
})

// 请求拦截器
request.interceptors.request.use(config => {
    if (hasToken()) {
        config.headers['Authorization'] = `Bearer ${getToken().token}`
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(response => {
    return response.data
}, async error => {
    const { response } = error
    //判断是否有错误信息 无错误信息 网络原因
    console.log(error);
    if (!error.response) {
        Toast.show({
            icon: 'fail',
            content: '服务器繁忙,稍后再试',
            maskClickable: false,
            duration: 1000
        })
        return Promise.reject(error)
    }
    // 如果错误信息不是401 提示相应错误 
    if (response.status !== 401) {
        Toast.show({
            icon: 'fail',
            content: response.status,
            maskClickable: false,
            duration: 1000
        })
        return Promise.reject(error)
    }
    // 如果错误是401 401是
    const { refresh_token } = getToken()
    if (response.status === 401) {
        // 如果没有refresh_token或者没有token 直接跳转登陆页面
        if (!refresh_token) {
            history.replace('/login', {
                from: history.location.pathname || '/home'
            })
            return Promise.reject(error)
        }
        // 如果response.status是401且有刷新token
        try {
            const res = await axios({
                url: baseURL + '/authorizations',
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${refresh_token}`
                }
            })
            // 组合token
            const tokenInfo = {
                token: res.data.data.token,
                refresh_token
            }
            // 保存本地token
            setToken(tokenInfo)
            // 保存redux的token
            store.dispatch(saveToken(tokenInfo))
            // 重新调用请求
            console.log(error.config);
            // headers里面保存的是之前的token  需要清空  再发一次请求会携带之前的token请求头
            return request({
                ...error.config,
                headers: {},
            });

        } catch {
            console.log(222);
            return Promise.reject(error)
        }
    }

    return Promise.reject(error)
})

export default request;